import 'package:flutter/material.dart';
import 'package:kasax_demos2/entry/data_posts_test.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax/utils/img_utils.dart';

/// ListView滚动监听:ScrollController 使用
class ListViewScrollDemo extends StatefulWidget {
  const ListViewScrollDemo({Key? key}) : super(key: key);

  @override
  _ListViewScrollDemoState createState() => _ListViewScrollDemoState();
}

class _ListViewScrollDemoState extends State<ListViewScrollDemo> {
  late ScrollController _scrollController;

  bool _isShowTop = false;

  @override
  void initState() {
    _scrollController = new ScrollController();
    _scrollController.addListener(() {
      /// 滑动距离大于1000显示滚动到顶部
      var tempSsShowTop = _scrollController.offset >= 1000;
      if (tempSsShowTop != _isShowTop) {
        setState(() {
          _isShowTop = tempSsShowTop;
        });
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ListView滚动控制"),
      ),
      body: Container(
          margin: EdgeInsets.only(top: 15),
          child: ListView(
            controller: _scrollController,
            children: PostsDatas.TEST_POSTS
                .map((e) => buildCardContainer(e, context))
                .toList(),
          )),
      floatingActionButton: !_isShowTop
          ? null
          : FloatingActionButton(
              onPressed: () {
                // 平滑滚动
                _scrollController.animateTo(0,
                    duration: Duration(seconds: 1), curve: Curves.linear);
              },
              child: Icon(Icons.upload_file),
            ),
    );
  }

  Widget buildCardContainer(Posts entry, BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, right: 10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ImageUtils.buildRoundImgByClip(entry.imageUrl),
          SizedBox(
            height: 15,
          ),
          Row(
            children: [
              CircleAvatar(
                backgroundColor: Colors.brown.shade800,
                backgroundImage: NetworkImage(entry.imageUrl),
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                entry.author,
                style: Theme.of(context).textTheme.subtitle,
              ),
              Expanded(
                  child: Text(
                entry.title,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                textAlign: TextAlign.end,
                style: Theme.of(context).textTheme.bodyText2,
              ))
            ],
          )
        ],
      ),
    );
  }
}
